<script setup lang="ts">
import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box'
import { useGuessPullupLoad } from '@/composables'
import {
  getMemberCartAPI,
  deleteMemberCartAPI,
  putMemberCartBySkuIdAPI,
  putMemberCartSelectedAPI,
} from '@/services'
import { useMemberStore } from '@/stores'
import type { CartItem } from '@/types'
import { onHide, onShow } from '@dcloudio/uni-app'
import type { UniSwipeActionInstance } from '@uni-helper/uni-ui-types'
import { storeToRefs } from 'pinia'
import { ref, computed, onMounted } from 'vue'

interface Props {
  // 是否适配底部安全区域
  safeAreaInsetBottom?: boolean
}
defineProps<Props>()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const cartList = ref<CartItem[]>([])
// 优化购物车空列表状态，默认展示列表
const isShowCart = ref(true)
// 购物车全选状态
const isSelectedAll = computed(
  () => cartList.value.length && cartList.value.every((v) => v.selected),
)
// 已选中商品列表
const selectedCartList = computed(() => cartList.value.filter((v) => v.selected))
// 已选中商品列表的总数量
const selectedCartListCount = computed(() =>
  selectedCartList.value.reduce((sum, item) => (sum += item.count), 0),
)
// 已选中商品列表的总价格
const selectedCartListMoney = computed(() =>
  selectedCartList.value.reduce((sum, item) => (sum += item.count * item.nowPrice), 0).toFixed(2),
)
// 获取购物车数据
const getMemberCartList = async () => {
  const res = await getMemberCartAPI()
  cartList.value = res.result
  isShowCart.value = res.result.length > 0
}
const memberStore = useMemberStore()
const { isLogin } = storeToRefs(memberStore)
onShow(() => {
  // 用户已登录才允许获取购物车数据
  if (isLogin.value) {
    getMemberCartList()
  }
})

// 删除购物车商品
const onCartDelete = (skuId: string) => {
  uni.showModal({
    title: '提示',
    content: '是否确定删除该商品？',
    confirmColor: '#27BA9B',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading()
        await deleteMemberCartAPI({ ids: [skuId] })
        // 重新获取购物车列表
        await getMemberCartList()
        // uni.hideLoading()
      }
    },
  })
}
// 修改商品数量
const onCountChange = (e: InputNumberBoxEvent) => {
  putMemberCartBySkuIdAPI(e.index, { count: e.value })
}
// 切换商品选中状态
const onSelectedChange = (item: CartItem) => {
  item.selected = !item.selected
  putMemberCartBySkuIdAPI(item.skuId, { selected: item.selected })
}
// 切换购物车全选状态
const onSelectedAllChange = () => {
  const _isSelectedAll = !isSelectedAll.value
  cartList.value.forEach((item) => {
    item.selected = _isSelectedAll
  })
  putMemberCartSelectedAPI({ selected: _isSelectedAll })
}
// 跳转商品结算页
const gotoPayment = () => {
  if (selectedCartListCount.value === 0) {
    return uni.showToast({
      icon: 'none',
      title: '请选择商品',
    })
  }
  uni.navigateTo({ url: '/pagesOrder/create/create' })
}

// 上拉加载猜你喜欢数据
const { guessRef, onScrolltolower } = useGuessPullupLoad()

const swipeActionRef = ref<UniSwipeActionInstance | null>(null)
onHide(() => {
  // 页面进入后台，关闭所有滑动块
  swipeActionRef.value?.closeAll?.()
})
</script>

<template>
  <scroll-view class="scroll-view" scroll-y enable-back-to-top @scrolltolower="onScrolltolower">
    <!-- 已登录: 显示购物车 -->
    <template v-if="isLogin">
      <!-- 购物车列表 -->
      <view class="cart-list" v-if="isShowCart">
        <!-- 优惠提示 -->
        <view class="tips">
          <text class="label">满减</text>
          <text class="desc">满1件, 即可享受9折优惠</text>
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action ref="swipeActionRef">
          <!-- 滑动操作项 -->
          <uni-swipe-action-item v-for="item in cartList" :key="item.skuId" class="cart-swipe">
            <!-- 商品信息 -->
            <view class="goods">
              <!-- 选中状态 -->
              <text
                :class="['checkbox', { checked: item.selected }]"
                @tap="onSelectedChange(item)"
              ></text>
              <navigator
                class="navigator"
                hover-class="none"
                :url="`/pages/goods/goods?id=${item.id}`"
              >
                <image class="picture" mode="aspectFill" :src="item.picture" />
                <view class="meta">
                  <text class="name ellipsis-1">{{ item.name }}</text>
                  <text class="attrsText ellipsis">{{ item.attrsText }}</text>
                  <text class="price">{{ item.nowPrice }}</text>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <vk-data-input-number-box
                  v-model="item.count"
                  disabledInput
                  :min="1"
                  :max="item.stock"
                  :index="item.skuId"
                  @plus="onCountChange"
                  @minus="onCountChange"
                />
              </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button class="button delete-button" @tap="onCartDelete(item.skuId)">删除</button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="/static/images/blank_cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选好货吧</text>
        <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
          <button class="button">去首页看看</button>
        </navigator>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view v-else class="login-blank">
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef"></XtxGuess>
    <!-- 底部占位空盒子 -->
    <view
      class="toolbar-height"
      :style="{ paddingBottom: safeAreaInsetBottom ? safeAreaInsets?.bottom + 'px' : 0 }"
    ></view>
  </scroll-view>
  <!-- 底部工具栏 -->
  <view
    v-if="isLogin"
    class="toolbar"
    :style="{ paddingBottom: safeAreaInsetBottom ? safeAreaInsets?.bottom + 'px' : 0 }"
  >
    <text :class="['all', { checked: isSelectedAll }]" @tap="onSelectedAllChange">全选</text>
    <text class="text">合计:</text>
    <text class="amount">{{ selectedCartListMoney }}</text>
    <view class="button-grounp">
      <view
        :class="['button', 'payment-button', { disabled: selectedCartListCount <= 0 }]"
        @tap="gotoPayment"
      >
        去结算({{ selectedCartListCount }})
      </view>
    </view>
  </view>
</template>

<style lang="scss">
/* 根元素 */
:host {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f8;
  overflow: hidden;
}

/* 滚动容器 */
.scroll-view {
  flex: 1;
  background-color: #f7f7f8;
}

/* 购物车列表 */
.cart-list {
  padding: 0 20rpx;

  /* 优惠提示 */
  .tips {
    display: flex;
    align-items: center;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;
    line-height: 1;

    .label {
      margin-right: 10rpx;
      padding: 7rpx 15rpx 5rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 4rpx;
      background-color: #27ba9b;
    }
  }

  /* 滑动操作项 */
  .cart-swipe {
    display: block;
    margin: 20rpx 0;

    .cart-swipe-right {
      display: flex;
      height: 100%;

      .button {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 50px;
        padding: 6px;
        font-size: 26rpx;
        color: #fff;
        line-height: 1.5;
        border-radius: 0;
      }

      .delete-button {
        background-color: #cf4444;
      }
    }
  }
}

/* 购物车商品 */
.goods {
  position: relative;
  // display: flex;
  padding: 20rpx 20rpx 20rpx 80rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .checkbox {
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80rpx;
    height: 100%;

    &::before {
      content: '\e6cd';
      font-family: 'erabbit' !important;
      font-size: 40rpx;
      color: #444;
    }

    &.checked::before {
      content: '\e6cc';
      color: #27ba9b;
    }
  }

  .navigator {
    display: flex;

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
    }

    .meta {
      position: relative;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;

      .name {
        font-size: 26rpx;
        color: #444;
      }

      .attrsText {
        // align-self: flex-start;
        position: absolute;
        top: 40rpx;
        left: 0;
        padding: 0 15rpx;
        font-size: 24rpx;
        color: #888;
        line-height: 1.6;
        border-radius: 4rpx;
        background-color: #f7f7f8;
      }

      .price {
        margin-top: 20rpx;
        font-size: 26rpx;
        color: #cf4444;
        line-height: 1;

        &::before {
          content: '￥';
          font-size: 80%;
        }
      }
    }
  }

  /* 商品数量 */
  .count {
    position: absolute;
    bottom: 20rpx;
    right: 5rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 220rpx;
    height: 48rpx;

    .text {
      padding: 0 20rpx;
      height: 100%;
      font-size: 32rpx;
      color: #444;
    }

    .input {
      height: 100%;
      font-size: 24rpx;
      color: #444;
      text-align: center;
      border-radius: 4rpx;
      background-color: #f6f6f6;
    }
  }
}

/* 空状态 */
.cart-blank,
.login-blank {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 60vh;

  .image {
    width: 400rpx;
    height: 281rpx;
  }

  .text {
    margin: 20rpx 0;
    font-size: 26rpx;
    color: #444;
  }

  .button {
    margin-top: 20rpx;
    width: 240rpx !important;
    height: 60rpx;
    font-size: 26rpx;
    color: #fff;
    line-height: 60rpx;
    border-radius: 60rpx;
    background-color: #27ba9b;
  }
}

/* 底部占位空盒子 */
.toolbar-height {
  box-sizing: content-box;
  height: 100rpx;
}

/* 底部工具栏 */
.toolbar {
  box-sizing: content-box;
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 1;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  height: 100rpx;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;

  .all {
    display: flex;
    align-items: center;
    margin-left: 25rpx;
    // font-size: 14px;
    font-size: 28rpx;
    color: #444;
  }

  .all::before {
    content: '\e6cd';
    margin-right: 8rpx;
    font-size: 40rpx;
    font-family: 'erabbit' !important;
  }

  .checked::before {
    content: '\e6cc';
    color: #27ba9b;
  }

  .text {
    margin-left: 32rpx;
    margin-right: 8rpx;
    // font-size: 14px;
    font-size: 28rpx;
    color: #444;
  }

  .amount {
    // font-size: 20px;
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }

    &::before {
      content: '￥';
      font-size: 80%;
    }
  }

  .button-grounp {
    display: flex;
    justify-content: space-between;
    margin-left: auto;
    // font-size: 13px;
    font-size: 26rpx;
    color: #fff;
    text-align: center;
    line-height: 72rpx;

    .button {
      margin: 0 10rpx;
      width: 240rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background-color: #27ba9b;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
</style>
